package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private UserServiceImpl userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FollowMapper followMapper;

    /**
     * 发布博客并保存到推送箱
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess) {
            return Result.fail("新增笔记失败");
        }
        // 查询博主粉丝列表并保存到推送箱
        Long userId = user.getId();
        List<Follow> follows = followMapper.selectFans(userId);
        for (Follow follow : follows) {
            // 获取粉丝 id
            Long fanId = follow.getUserId();
            String key = FEED_KEY + fanId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 滚动分页查询关注
     * @param lastId
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long lastId, Integer offset) {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 滚动分页查询推送箱是否有博客  zrevrangebyscore key max(时间戳) min(0) LIMIT offset count(每次分页查询的数量)
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, lastId, offset, 3);
        // 没有直接放行
        if(typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 有，查询博客 id
        long minTime = 0L;
        int count = 1;
        List<Long> ids = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 获取 id
            Long id = Long.valueOf(typedTuple.getValue());
            ids.add(id);
            // 获取最后出现的时间戳分数
            long time = typedTuple.getScore().longValue();
            // 计算偏移量 offset
            if(minTime == time) {
                count++;
            } else {
                count = 1;
                minTime = time;
            }
        }
        // 根据博客 id 查询并封装博客
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        // 查询博客是否被点赞
        for (Blog blog : blogs) {
            // 查用户
            queryBlogUser(blog);
            // 查询是否被点赞
            isBlogLiked(blog);
        }
        // 返回博客列表
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(count);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }

    /**
     * 更新点赞
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        // 1. 获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        // 博客的 key
        String key = BLOG_LIKED_KEY + id;
        // 2. 判断当前用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score == null) {
            // 3. 当前用户未点赞
            // 3.1 点赞次数 +1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            // 3.2 把当前点赞用户 id 存入 zset集合
            if(isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 4. 当前用户已经点赞
            // 4.1 点赞次数 -1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            // 4.2 把用户 id 从 set 集合中删除
            if(isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 查看博客
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        // 查博客
        Blog blog = getById(id);
        if(blog == null) {
            return Result.fail("北极不存在");
        }
        // 查用户
        queryBlogUser(blog);
        // 查询是否被点赞
        isBlogLiked(blog);

        return Result.ok(blog);
    }

    /**
     * 点赞用户排序显示前五名
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        // 获取点赞用户前五名列表
        Set<String> list = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        // 判断点赞用户是否存在
        if(list == null || list.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 解析出点赞用户 id
        List<Long> ids = list.stream().map(Long::valueOf).collect(Collectors.toList());
        // 根据点赞用户 id 查询用户
        List<User> users = userService.listByIds(ids);
        // 封装用户为 DTO 对象
        List<Object> userDTO = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTO);
    }

    /**
     * 判断 blog 是否被点赞
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        // 1. 获取当前登录用户
        UserDTO user = UserHolder.getUser();
        if(user == null) {
            return;
        }
        Long userId = user.getId();

        // 博客的 key
        String key = BLOG_LIKED_KEY + blog.getId();
        // 2. 判断当前用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        blog.setIsLike(score != null);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result queryBlogByUserId(Long id, Integer current) {
        Page<Blog> page = this.query().eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }
}
